//
//  ZImageLoopView.m
//  ZImageLoopViewDemo
//
//  Created by Meniny on 14/12/24.
//  Copyright (c) 2014年 Zero. All rights reserved.
//

#import "ZImageLoopView.h"

#define TitleLabelHeight 44

@interface ZImageLoopView () {
    int _currentPage;
    int _scrollPageIndex;
    NSTimer *_scrollTimer;
    NSTimeInterval _loopTime;
}

@end

@implementation ZImageLoopView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (void)setup {
    self.pagingEnabled = YES;
    self.delegate = self;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    
    _scrollPageIndex = 1;
}

- (void)reloadData {
    if ( !_imageArr) return;
    
    if (_scrollTimer) {
        [self releaseTimer];
    }
    
    // 清除原先添加的所有子视图
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    
    // 为scrollView添加每一页的内容
    int i = 0;
    CGFloat width = self.frame.size.width;
    for (UIImage *image in _imageArr) {
        CGRect frame = CGRectMake(i * width, 0, width, self.frame.size.height);
        UIButton *picBtn = [self picBtnWithFrame:frame Image:image Index:i];
        
        [self addSubview:picBtn];
        i++;
    }
    
    // 默认显示第一张图片
    [self setContentSize:CGSizeMake(width * _imageArr.count, self.frame.size.height)];
    [self setContentOffset:CGPointMake(width, 0)];
    
    // 默认开启定时器
    _scrollTimer = [NSTimer scheduledTimerWithTimeInterval:self.loopTime target:self selector:@selector(scrollTimerAction) userInfo:nil repeats:YES];
    
    NSLog(@"%@", self.subviews);
}

- (UIButton *)picBtnWithFrame:(CGRect)frame Image:(UIImage *)image Index:(NSInteger)index {
    UIButton *picBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    picBtn.frame = frame;
    [picBtn setTag:index];
    [picBtn setImage:image forState:UIControlStateNormal];
    picBtn.adjustsImageWhenHighlighted = NO;
    [picBtn addTarget:self action:@selector(picBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([self.imageLoopViewDelegate respondsToSelector:@selector(imageLoopView:titleLabelForImageAtIndex:)]) {
        UILabel *titleLabel = [self.imageLoopViewDelegate imageLoopView:self titleLabelForImageAtIndex:index];
        
        if (CGRectEqualToRect(titleLabel.frame, CGRectZero)) {
            titleLabel.frame = CGRectMake(0, self.frame.size.height - TitleLabelHeight, self.frame.size.width, TitleLabelHeight);
        }
        
        [picBtn addSubview:titleLabel];
    }
    
    return picBtn;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat width = self.frame.size.width;
    // 显示scrollView的第一张图片(最后一张图片)时, 偏移到scrollView的倒数第二张图片(最后一张图片)
    if (scrollView.contentOffset.x <= 0) {
        [self setContentOffset: CGPointMake(width * (_imageArr.count - 2), 0) animated:NO];
    }
    
    // 显示scrollView的最后一张图片(第一张图片)时, 偏移到scrollView的第二张图片(第一张图片)
    if (scrollView.contentOffset.x >= width * (_imageArr.count - 1)) {
        [self setContentOffset:CGPointMake(width, 0) animated:NO];
    }
    
    _currentPage = self.contentOffset.x / width - 1;    // 索引从0开始, 要-1
    // _currentPage为0时(索引为1的图片), 定时器播放_currentPage为1(索引为2的图片)
    _scrollPageIndex = _currentPage == 0 ? 2 : _currentPage + 2;
}

#pragma mark - 定时器相关

/** 拖拽结束后开启定时器 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    _scrollTimer = [NSTimer scheduledTimerWithTimeInterval:self.loopTime target:self selector:@selector(scrollTimerAction) userInfo:nil repeats:YES];
}

/** 开始拖拽时停止定时器 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (_scrollTimer) {
        [self releaseTimer];
    }
}

- (void)releaseTimer {
    [_scrollTimer invalidate];
    _scrollTimer = nil;
}

/** 定时器执行方法 */
- (void)scrollTimerAction {
    // 定时器播放时只需要 first, second, ...... last, first, 从1开始
    [self setContentOffset:CGPointMake(self.bounds.size.width * _scrollPageIndex, 0) animated:YES];
    if (_scrollPageIndex > self.imageArr.count - 1) {
        _scrollPageIndex = 1;
    } else {
        _scrollPageIndex++;
    }
}

#pragma mark - 图片点击响应事件

- (void)picBtnAction:(UIButton *)sender {
    if ([self.imageLoopViewDelegate respondsToSelector:@selector(imageLoopView:didClickImageAtIndex:)]) {
        [self.imageLoopViewDelegate imageLoopView:self didClickImageAtIndex:sender.tag - 1];
    }
}

#pragma makr - Getter & Setter

- (void)setImageArr:(NSArray *)imageArr {
    // 更新图片数组, 添加最后一张图与第一张图
    NSMutableArray *tempImageArr = [NSMutableArray array];
    [tempImageArr addObject:[imageArr lastObject]];
    [tempImageArr addObjectsFromArray:imageArr];
    [tempImageArr addObject:[imageArr firstObject]];
    _imageArr = tempImageArr;
    
    [self reloadData];
}

- (NSTimeInterval)loopTime {
    if (_loopTime == 0) {
        return 2;
    }
    return _loopTime;
}

- (void)setLoopTime:(NSTimeInterval)loopTime {
    _loopTime = loopTime;
    [self reloadData];
}

@end







